from rest_framework import serializers
from .models import student_info, Study_Note, student_course_info, student_course_LearningProgress, CourseProgress, StudyPlan


class StudentInfoSerializer(serializers.ModelSerializer):
    hobbies = serializers.JSONField()

    class Meta:
        model = student_info
        fields = '__all__'
        extra_kwargs = {
            'stu_id': {'read_only': True}
        }


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = student_info
        fields = (
            'stu_id', 'stu_name', 'stu_age', 'seat_id', 'stu_grade', 'stu_college', 'stu_class', 'stu_gender',
            'stu_age',
            'stu_tel', 'stu_address', 'stu_email', 'hobby')


class StudyNoteSerializer(serializers.ModelSerializer):
    course_name = serializers.CharField(source='point.chapter.course.course_name', read_only=True)

    class Meta:
        model = Study_Note
        fields = ['id', 'note_title', 'note_content', 'created_at', 'course_name']
        read_only_fields = ['created_at']


class StudentCourseInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = student_course_info
        fields = '__all__'


class ProgressSerializer(serializers.ModelSerializer):
    class Meta:
        model = student_course_LearningProgress
        fields = ['point', 'is_completed']


class StudyPlanSerializer(serializers.ModelSerializer):
    """学习计划序列化器"""
    class Meta:
        model = StudyPlan
        fields = '__all__'
        
    def to_representation(self, instance):
        """自定义输出格式"""
        data = super().to_representation(instance)
        # 将时间格式化为字符串
        if 'start_time' in data:
            data['start_time'] = instance.start_time.strftime('%H:%M')
        if 'end_time' in data:
            data['end_time'] = instance.end_time.strftime('%H:%M')
        # 添加格式化后的周期信息
        if instance.plan_type == 'periodic' and instance.cycle_value and instance.cycle_unit:
            data['cycle'] = f"{instance.cycle_value} {instance.cycle_unit}"
        return data
